package midone.exchangeskill.net.api;

import midone.exchangeskill.bean.IndexGoodsBean;
import midone.exchangeskill.bean.ResponseBean;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static midone.exchangeskill.net.api.NetConstants.CODE_SUCCESS;

/**
 * Created by NekoNeko on 2016/11/7.
 */

public class ApiManager {
    static String TAG = "ApiManager";
    ApiService apiService;

    public ApiManager(ApiService apiService) {
        this.apiService = apiService;
    }

    /**
     * 封装Rx回调为UrlResponse
     *
     * @param observable
     * @return
     */

    private static UrlResponse response(Observable observable) {
        final UrlResponse urlResponse = new UrlResponse();
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1() {
            @Override
            public void call(Object o) {
                urlResponse.getResCall().onResponse();
                ResponseBean baseBean = (ResponseBean) o;
                if (CODE_SUCCESS.equals(baseBean.getCode())) {
                    urlResponse.getResCall().onSuccess(o);
                } else {
                    urlResponse.getResCall().onFailed(baseBean.getMsg());
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                urlResponse.getResCall().onError(throwable);
            }
        });
        return urlResponse;
    }

    public UrlResponse<IndexGoodsBean> getIndexGoodsData(String catId, String sort, String pageNum) {
        return response(apiService.getIndexGoodsData(catId, sort, pageNum));
    }
}
